//
//  XJHLabel.swift
//  PublicPod
//
//  Created by 许俊华 on 2021/9/6.
//

import UIKit

public typealias LabelClickBlock = ()->Void
public typealias LabelLongPressBlock = () -> Void

public class XJHLabel: UILabel {

    public var clickBlock:LabelClickBlock?
    public var longPressBlock:LabelLongPressBlock?
    
    // 最大宽度
    private var _maxWidth:CGFloat?
    public var maxWidth:CGFloat {
        set {
            _maxWidth = newValue
            self.numberOfLines = 0
            self.preferredMaxLayoutWidth = _maxWidth!
            self.setContentHuggingPriority(.required, for: .vertical)
        }
        get {
            return _maxWidth!
        }
    }
    
    // 边框颜色
    private var _borderColor:UIColor?
    public var borderColor:UIColor {
        set {
            _borderColor = newValue
            self.layer.borderColor = _borderColor?.cgColor
        }
        get {
            return _borderColor!
        }
    }
    
    // 边框宽度
    private var _borderWidth:CGFloat?
    public var borderWidth:CGFloat {
        set {
            _borderWidth = newValue
            self.layer.borderWidth = _borderWidth!
        }
        get {
            return _borderWidth!
        }
    }
    
    // 圆角大小
    private var _cornerSize:CGFloat?
    public var cornerSize:CGFloat {
        set {
            _cornerSize = newValue
            self.layer.cornerRadius = _cornerSize!
            self.layer.masksToBounds = true
        }
        get {
            return _cornerSize!
        }
    }
    
    // 垂直文本
    private var _verticalText:String?
    public var verticalText:String {
        set {
            _verticalText = newValue
            let str:NSMutableString = NSMutableString.init(string: _verticalText!)
            for i in 0..._verticalText!.count {
                str .insert("\n", at: i*2-1)
            }
            _verticalText = str as String
            self.numberOfLines = 0
        }
        get {
            return _verticalText!
        }
    }
    
    // 初始化
    public class func labelWithFontAndTextColor(font:UIFont, textColor:String) -> XJHLabel {
        let label:XJHLabel = XJHLabel.init()
        label.font = font;
        label.textColor = UIColor.colorWithHexColor(hexadecimal: textColor);
        
        //点击事件
        let tap = UITapGestureRecognizer.init(target: label, action: #selector(clickAction))
        //绑定tap
        label.addGestureRecognizer(tap)
        
        // 长按事件
        let longPress = UILongPressGestureRecognizer.init(target: label, action: #selector(longPressAction(longPressGesture:)))
        label.addGestureRecognizer(longPress)
        return label;
    }
    
    // MARK:点击事件
    @objc fileprivate func clickAction() -> Void {
        if self.clickBlock != nil {
            self.clickBlock!()
        }
    }
    
    // MARK:长按事件
    @objc fileprivate func longPressAction(longPressGesture:UILongPressGestureRecognizer) -> Void {
        if longPressGesture.state == .began {
            if self.longPressBlock != nil {
                self.longPressBlock!()
            }
        }
    }
    
    /**
    *  单纯改变一句话中的某些字的颜色
    *
    *  @param color    需要改变成的颜色
    *  @param totalStr 总的字符串
    *  @param subArray 需要改变颜色的文字数组
       @param lineSpace 行间距
    */
    public func setSubStringColorWithColor(color:UIColor, totalString:String, subStringArray:Array<String>, lineSpace:CGFloat) -> Void {
        let attributedStr:NSMutableAttributedString = NSMutableAttributedString.init(string: totalString)
        
        for rangeString in subStringArray {
            let range = totalString.rangeOfSubString(subString: rangeString)
            
            attributedStr.addAttribute(.foregroundColor, value: color, range: range)
        }
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = lineSpace
        attributedStr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, totalString.count))
        
        self.attributedText = attributedStr;
    }
    
    /**
     *  更改行间距
     *
     *  @param totalString 需要改变的字符串
     *  @param lineSpace   行间距
     *
     */
    public func setLineSpaceWithTotalString(totalString:String, lineSpace:CGFloat) -> Void {
        let attributedStr:NSMutableAttributedString = NSMutableAttributedString.init(string: totalString)
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = lineSpace
        attributedStr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, totalString.utf16.count))
        
        self.attributedText = attributedStr
        
    }
    
    /**
     * 改变某些文本的颜色和行间距,字体
     * @param color         需要变成的颜色
     * @param font          需要变成的字体
     * @param totalStr      总的字符串
     * @param subArray      需要改变颜色的文字数组  也可以传总的字符串
     * @param lineSpace     行间距
     */
    public func setLineSpaceAndSubStringColorWithColor(color:UIColor, font:UIFont, totalString:String, subStringArray:Array<String>, lineSpace:CGFloat) -> Void {
        let attributedStr:NSMutableAttributedString = NSMutableAttributedString.init(string: totalString)
        
        for rangeString in subStringArray {
            let range = totalString.rangeOfSubString(subString: rangeString)
            
            attributedStr.addAttribute(.foregroundColor, value: color, range: range)
            
            attributedStr.addAttribute(.font, value: font, range: range)
        }
        
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = lineSpace
        attributedStr.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, totalString.utf16.count))
        
        
        self.attributedText = attributedStr;
    }
    
    /**
    固定宽度时，文字两边居中
    */
    public func changeAlignmentRightandLeft() -> Void {
        let textString:NSString = self.text! as NSString
        
        
        let textSize = textString.boundingRect(with: CGSize.init(width: self.frame.size.width, height: CGFloat(MAXFLOAT)), options:NSStringDrawingOptions(rawValue: NSStringDrawingOptions.RawValue(UInt8(NSStringDrawingOptions.usesFontLeading.rawValue) | UInt8(NSStringDrawingOptions.truncatesLastVisibleLine.rawValue) | UInt8(NSStringDrawingOptions.usesLineFragmentOrigin.rawValue))), attributes: [NSAttributedString.Key.font:self.font as Any], context: nil)
        
        // 每个字符之间，平均的宽度（点坐标）
        let margin:CGFloat = (self.frame.size.width-textSize.size.width)/CGFloat((textString.length-1))
        
        let attributeString:NSMutableAttributedString = NSMutableAttributedString.init(string: self.text!)
        
        attributeString.addAttribute(kCTKernAttributeName as NSAttributedString.Key, value: margin, range: NSMakeRange(0, self.text!.count-1))
        
        self.attributedText = attributeString
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
